package org.example.forum.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Article;
import org.example.forum.model.ArticleReply;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.services.IArticleReplyService;
import org.example.forum.services.IArticleService;
import org.example.forum.services.IBoardService;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@Tag(name = "帖子接口")
@RequestMapping("/article")
public class ArticleController {
    /**
     * 发表帖子
     * @param request
     * @param title   文章标题
     * @param content 文章内容
     * @param boardId 板块Id
     * @return
     */

    @Resource
    private IBoardService boardService;

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleReplyService articleReplyService;

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;


    @Operation(summary ="测试发帖")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @RequestParam("title") @NonNull String title,
                             @RequestParam("content") @NonNull String content,
                             @RequestParam("boardId") @NonNull Long boardId) {
        //通过session获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户是否被禁言
        if(user.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }

        //通过boardId获取板块信息
        Board board = boardService.selectById(boardId);
        //校验板块信息
        if(board == null || board.getState() == 1
            ||board.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_BANNED));
        }

        // 封装文章对象
        Article article = new Article();
        article.setTitle(title); // 标题
        article.setContent(content); // 正文
        article.setBoardId(boardId); // 版块Id
        article.setUserId(user.getId()); // 作者Id
        // 调用Service
        articleService.create(article);
        // 响应
        return AppResult.success();

    }


    @Operation(summary = "获取帖子列表")
    @GetMapping("/getList")
    public AppResult<List<Article>> getListByBoardId(
            @Parameter(description = "板块Id",required = false)
            @RequestParam(value = "boardId",required = false) Long boardId)  {

        List<Article> articles = null;
        //判断传入boradId是否为空
        if(boardId == null){
            // 为空 查询所有
            articles = articleService.selectAll();
        }else{
            //不为空 按照boardId查询帖子列表
            articles = articleService.selectAllByBoardId(boardId);
        }
        //校验列表是否为空
        if(articles == null){
            //为空 
           articles = new ArrayList<>();//赋一个新的空表
        }
        //返回结果
        return AppResult.success(articles);

    }


    @Operation(summary = "查询帖子详情")
    @GetMapping("/getDetail")
    public AppResult getDetail(HttpServletRequest request,@Parameter(description = "帖子id")
                                   @RequestParam(value = "id") @NonNull Long id){
        //根据session获取用户信息
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //获取帖子信息
        Article article = articleService.selectDetailById(id);
        //判断帖子是否为空
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断登陆用户是否为帖子作者
        if(user.getId() == article.getUserId()){
            //标识为作者
            article.setOwn(true);
        }else{
            article.setOwn(false);
        }
        return AppResult.success(article);
    }


    @Operation(summary = "更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @Parameter(description = "帖子id") @RequestParam(value = "id") @NonNull Long id,
                            @Parameter(description = "帖子标题") @RequestParam(value = "title") @NonNull String title,
                            @Parameter(description = "帖子内容") @RequestParam(value = "content") String content){
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1 || user.getId() == null){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //获取帖子信息
        Article article = articleService.selectById(id);
        //判断帖子是否为空
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断用户是否为作者
        if(user.getId() != article.getUserId()){
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //判断帖子状态
        if(article.getState() == 1 || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //调用DAO
        articleService.modify(id,title,content);
        //打印日志
        log.info("帖子更新成功:" + " id: " + id + " ,title: " + title + " ,content: " + content);
       return AppResult.success();
    }

    @Operation(summary = "点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(  HttpServletRequest request,
            @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //校验参数合法性
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //校验用户状态
        if(user.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));

        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }


    @Operation(summary ="删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request,
                                @Parameter(description = "帖子id")@RequestParam("id") @NonNull Long id) {
        // 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 表示用户禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            // 帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 校验当前登录的用户是不是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用Service
        articleService.deleteById(id);
        // 返回操作成功
        return AppResult.success();
    }


    @Operation(summary = "获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId (
            @Parameter(description = "帖子Id") @RequestParam("articleId") @NonNull Long articleId) {
        // 校验帖子是否存在
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            // 返回错误提示
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 调用Service
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        // 返回结果
        return AppResult.success(articleReplies);

    }
    @Operation(summary = "获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                    @Parameter(description = "用户Id")
                                                    @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }

}
